import os
import shutil
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import sys
from pathlib import Path

current_dir = Path.cwd()
print(f"Current Directory: {current_dir}")

class SyncHandler(FileSystemEventHandler):
    def __init__(self, source_dir, dest_dir):
        self.source_dir = source_dir
        self.dest_dir = dest_dir

    def sync_file(self, src_path, dest_path):
        """Synchronize a file."""
        dest_folder = os.path.dirname(dest_path)
        if not os.path.exists(dest_folder):
            os.makedirs(dest_folder)
        shutil.copy2(src_path, dest_path)
        print(f"Synced file: {src_path} -> {dest_path}")

    def on_created(self, event):
        if not event.is_directory:
            src_path = event.src_path
            dest_path = src_path.replace(self.source_dir, self.dest_dir, 1)
            self.sync_file(src_path, dest_path)

    def on_modified(self, event):
        if not event.is_directory:
            src_path = event.src_path
            dest_path = src_path.replace(self.source_dir, self.dest_dir, 1)
            self.sync_file(src_path, dest_path)

    def on_deleted(self, event):
        dest_path = event.src_path.replace(self.source_dir, self.dest_dir, 1)
        if os.path.exists(dest_path):
            os.remove(dest_path)
            print(f"Deleted file: {dest_path}")

if __name__ == "__main__":
     # Get the parameters passed to the program
    args = sys.argv

    # Check if the number of arguments is sufficient
    if len(args) < 3:  # 1 for the script name and 2 for parameters
        print("至少2个参数")
        exit(1)

    # Extract parameters
    source_dir = args[1]
    dest_dir = args[2]

    # Perform actions with the parameters
    print(f"源目录: {source_dir}")
    print(f"目标目录: {dest_dir}")

    # source_dir = r"C:\path\to\source"
    # dest_dir = r"\\server2\shared\destination"

    event_handler = SyncHandler(source_dir, dest_dir)
    observer = Observer()
    observer.schedule(event_handler, source_dir, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()